<template>
  <div class="app-container towSearchHeader">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select filterable placeholder="选择门店" v-model="formInline.store_id" style="width:300px">
            <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker :clearable="false" v-model="pickerDate" value-format="yyyy-MM-dd" type="date" style="width:150px" placeholder="选择日期"
            :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <div class="contrast">
        <el-button @click="cancel" size="small" type="primary" :disabled="isCancle">取消对比</el-button>
        <el-button @click="goCheck" size="small" type="primary">对比</el-button>
        <!-- 筛选弹窗 -->
        <div v-show="checkDialog" class="check_dialog">
          <div class="title">
            <span></span>
            <span @click="colseCheckDialog"><i class="el-icon-close"></i></span>
          </div>
          <div style="margin:10px 0;text-align: left;">
            <el-radio-group v-model="checkRadio">
              <el-radio :label="1">在场人数</el-radio>
              <el-radio :label="4">儿童在场人数</el-radio><br>
              <el-radio style="margin:10px 0" :label="2">入场人数</el-radio>
              <el-radio :label="5">儿童入场人数</el-radio><br>
              <el-radio :label="3">出场人数</el-radio>
              <el-radio :label="6">儿童出场人数</el-radio>
            </el-radio-group><br>
            <el-select style="width:240px;margin-top:10px;" v-model="check_date" multiple :multiple-limit="6" placeholder="请选择日期">
              <el-option v-for="item in contrast_date_list" :key="item.value" :label="item.value" :disabled="item.value==formInline.start_time"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <el-button @click="goContrast" size="small" type="primary">确认</el-button>
        </div>
      </div>
      <div style="background:#fff">
        <WristbandChart :chartData="chartData" :chartSet="chartSet" :chartType="chartType"></WristbandChart>
      </div>
      <!-- 表格 -->
      <el-table style="margin:50px 0" highlight-current-row :data="list" v-loading.body="listLoading" border size="small">
        <el-table-column align="center" prop="time" label="日期" sortable sort-by="index"></el-table-column>
        <el-table-column align="center" label="入场人数">
          <el-table-column align="center" prop="in_child" label="儿童人数" sortable></el-table-column>
          <el-table-column align="center" prop="in_player" label="总入场人数" sortable></el-table-column>
        </el-table-column>
        <el-table-column align="center" label="出场人数">
          <el-table-column align="center" prop="out_child" label="儿童人数" sortable></el-table-column>
          <el-table-column align="center" prop="out_player" label="总出场人数" sortable></el-table-column>
        </el-table-column>
        <el-table-column align="center" label="在场人数">
          <el-table-column align="center" prop="all_on_child" label="儿童人数" sortable></el-table-column>
          <el-table-column align="center" prop="all_on_hand" label="总在场人数" sortable></el-table-column>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import { getStore, getChartData } from '@/api/dashboard/wristbandAnalyze';
import WristbandChart from './components/WristbandChart';
export default {
  components: {
    WristbandChart
  },
  data() {
    return {
      list: null,
      check_date: [],
      contrast_date_list: [],
      checkRadio: 1,
      remark: [{ name: '备注', text: '' }],
      listLoading: false,
      checkDialog: false,
      isCancle: true,
      storeList: null,
      contrastStartTime: '',
      contrastEndTime: '',
      look_del: '1',
      formInline: {
        store_id: '',
        start_time: ''
      },
      chartData: {
        dimensions: [],
        source: []
      },
      currentData: [],
      oneDayData: [],
      fullContrastData: [],
      currentCheckTime: '',
      oldData: {
        store_id: '',
        start_time: '',
        checkTime: '',
        checkType: ''
      },
      chartSet: {
        xName: '时间',
        yName: '人数'
      },
      chartType: [],
      oneDayType: [
        { type: 'bar', color: '#fa9d58', barGap: '100%' },
        { type: 'bar', color: '#fac158', z: 1, barGap: '100%' },
        { type: 'bar', color: '#93bcf5', barGap: '100%' },
        { type: 'bar', color: '#8cd4fd', z: 1, barGap: '100%' },
        { type: 'line', color: '#9e95f1' },
        { type: 'line', color: '#f99ae4' }
      ],
      lineColor: ['#4492fb', '#e1cefd', '#fccff7', '#edc5cb', '#c3dedc', '#ffdcaf', '#d0ccc3'],
      contrastType: [],
      pickerDate: new Date().toISOString().split('T')[0],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() || time.getTime() < Date.now() + 8.64e7 * -33;
        }
      }
    };
  },
  activated() {
    if (this.$route.params.store_id || !this.storeList) {
      this.getstore();
    }
  },
  created() {
    this.getContrastDateList();
  },
  methods: {
    lookDelChange() {
      this.getStore();
    },
    getContrastDateList() {
      let now = Date.now();
      for (let i = 0; i < 33; i++) {
        let date = {};
        date.value = new Date(Date.now() - 8.64e7 * i).toISOString().split('T')[0];
        this.contrast_date_list.push(date);
      }
    },
    getstore() {
      getStore({ category_id: 422 }).then(response => {
        this.storeList = response;
        let data = response.filter(res => res.id == this.$store.getters.optionId);
        if (data.length > 0) {
          this.formInline.store_id = data[0].id;
        } else {
          if (this.storeList.length > 0) {
            this.formInline.store_id = this.storeList[0].id;
          }
        }

        if (this.$route.params.store_id) {
          this.formInline.store_id = this.$route.params.store_id;
        }
        if (this.list == null || this.$route.params.store_id) this.searchClick();
      });
    },
    // 搜索
    searchClick() {
      if (this.formInline.store_id == '') {
        this.$message({ type: 'error', message: '请选择门店' });
        return;
      }
      this.formInline.start_time = this.pickerDate.replace(/\./g, '-');
      this.check_date = [];
      this.checkRadio = 1;
      this.fetchData();
    },
    goCheck() {
      this.checkDialog = true;
    },
    colseCheckDialog() {
      this.checkDialog = false;
    },
    goContrast() {
      if (this.check_date.length <= 0) {
        this.$message.error('请选择对比日期');
        return;
      }
      this.checkDialog = false;
      this.contrastData();
    },
    cancel() {
      this.checkDialog = false;
      this.isCancle = true;
      this.searchClick();
    },
    // 列表获取
    fetchData() {
      this.chartType = this.oneDayType;
      this.chartSet.yName = '人数';
      if (this.oldData.store_id == this.formInline.store_id && this.oldData.start_time == this.formInline.start_time) {
        this.chartData = this.currentData;
        return;
      }
      this.list = [];
      this.chartData = {
        dimensions: [],
        source: []
      };
      this.currentData = this.chartData;
      getChartData(this.formInline).then(res => {
        if (res.code == 1) {
          this.oldData.store_id = this.formInline.store_id;
          this.oldData.start_time = this.formInline.start_time;
          let data = res.message[0].data;
          if (data.length <= 0) {
            return;
          }
          data.forEach(val => {
            val.hm = val.time.split(' ')[1];
            val.on_hand = val.in_player - val.out_player;
            val.in_player *= 1;
            val.out_player *= 1;
            val.in_child = val.baby_in_player * 1;
            val.out_child = val.baby_out_player * 1;
            val.on_child = val.in_child - val.out_child;
          });
          let all = 0;
          let all_child = 0;
          data.forEach(val => {
            all += val.on_hand;
            val.all_on_hand = all;
            all_child += val.on_child;
            val.all_on_child = all_child;
          });
          this.list = data;
          let start = data[0].hm;
          let end = data[data.length - 1].hm;
          let fullData = this.getFulltData(start, end, data);
          this.oneDayData = fullData;
          let source = [];
          for (let val of fullData) {
            let obj = {
              time: val.hm,
              总入场人数: val.in_player,
              儿童入场人数: val.in_child,
              总出场人数: val.out_player,
              儿童出场人数: val.out_child,
              总在场人数: val.all_on_hand,
              儿童在场人数: val.all_on_child
            };
            source.push(obj);
          }
          let chartData = {
            dimensions: ['time', '总入场人数', '儿童入场人数', '总出场人数', '儿童出场人数', '总在场人数', '儿童在场人数'],
            source
          };
          this.chartData = chartData;
          this.currentData = chartData;
        }
      });
      this.isCancle = true;
    },
    //对比数据获取
    contrastData() {
      this.isCancle = false;
      let checkTime = this.check_date.sort((a, b) => new Date(a).getTime() - new Date(b).getTime()).join(',');
      if (this.oldData.checkTime == checkTime) {
        let nullData = this.fullContrastData;
        if (this.oldData.checkType != this.checkRadio) {
          if (this.fullContrastData.length != 0) this.contrastChartData(this.fullContrastData, this.checkRadio);
        }
        return;
      }
      this.chartData = {
        dimensions: [],
        source: []
      };
      getChartData({ store_id: this.formInline.store_id, start_time: checkTime }).then(res => {
        if (res.code == 1) {
          this.oldData.checkTime = checkTime;
          this.oldData.checkType = this.checkRadio;
          let nullData = res.message.filter(val => val.data.length == 0);
          if (nullData.length == res.message.length) {
            return;
          }

          res.message.forEach((val, i) => {
            let data = val.data;
            if (data.length == 0) {
              let obj = {
                time: this.check_date[i] + ' 12:00',
                in_player: 0,
                out_player: 0,
                in_child: 0,
                out_child: 0
              };
              data.push(obj);
            }
            data.forEach(val => {
              val.date = val.time.split(' ')[0];
              val.hm = val.time.split(' ')[1];
              val.on_hand = val.in_player - val.out_player;
              val.in_player *= 1;
              val.out_player *= 1;
              val.in_child = val.baby_in_player * 1;
              val.out_child = val.baby_out_player * 1;
              val.on_child = val.in_child - val.out_child;
            });
            let all = 0;
            let all_child = 0;
            data.forEach(val => {
              all += val.on_hand;
              val.all_on_hand = all;
              all_child += val.on_child;
              val.all_on_child = all_child;
            });
          });
          res.message.sort((a, b) => a.data[0].hm.replace(':', '') - b.data[0].hm.replace(':', ''));
          this.contrastStartTime = res.message[0].data[0].hm;
          res.message.sort((a, b) => b.data[b.data.length - 1].hm.replace(':', '') - a.data[a.data.length - 1].hm.replace(':', ''));
          this.contrastEndTime = res.message[0].data[res.message[0].data.length - 1].hm;
          if (this.contrastStartTime.replace(':', '') > this.oneDayData[0].hm.replace(':', '')) {
            this.contrastStartTime = this.oneDayData[0].hm;
          }
          if (this.contrastEndTime.replace(':', '') < this.oneDayData[this.oneDayData.length - 1].hm.replace(':', '')) {
            this.contrastEndTime = this.oneDayData[this.oneDayData.length - 1].hm;
          }
          //补齐数据
          let fullData = [];
          res.message.forEach(data => {
            let complementData = this.getFulltData(this.contrastStartTime, this.contrastEndTime, data.data);
            fullData.push(complementData);
          });
          this.fullContrastData = fullData;
          this.contrastChartData(this.fullContrastData, this.checkRadio);
        }
      });
    },
    //折线图对比数据
    contrastChartData(data, checkType) {
      let key = 'all_on_hand';
      let type = '总在场人数';
      this.chartSet.yName = '总在场人数';
      if (checkType == 2) {
        key = 'in_player';
        type = '总入场人数';
        this.chartSet.yName = '总入场人数';
      }
      if (checkType == 3) {
        key = 'out_player';
        type = '总出场人数';
        this.chartSet.yName = '总出场人数';
      }
      if (checkType == 4) {
        key = 'all_on_child';
        type = '儿童在场人数';
        this.chartSet.yName = '儿童在场人数';
      }
      if (checkType == 5) {
        key = 'in_child';
        type = '儿童入场人数';
        this.chartSet.yName = '儿童入场人数';
      }
      if (checkType == 6) {
        key = 'out_child';
        type = '儿童出场人数';
        this.chartSet.yName = '儿童出场人数';
      }
      let currentData = this.getFulltData(this.contrastStartTime, this.contrastEndTime, this.oneDayData);
      let source = [];
      for (let i in currentData) {
        let obj = {
          time: currentData[i].hm,
          [currentData[i].date]: currentData[i][key]
        };
        for (let val of data) {
          obj[val[i].date] = val[i][key];
        }
        source.push(obj);
      }
      let dimensions = ['time', this.formInline.start_time];
      for (let val of this.check_date) {
        dimensions.push(val);
      }
      let chartType = [];
      for (let i = 0; i <= this.check_date.length; i++) {
        let item = {};
        item.type = 'line';
        item.color = this.lineColor[i];
        chartType.push(item);
      }
      this.chartType = chartType;
      this.chartData = { dimensions, source };
      this.oldData.checkType = checkType;
    },
    //补全数据
    getFulltData(start, end, data) {
      let complementData = [];
      let i = 0;
      let start_time = new Date('2000-01-01 ' + start).getTime();
      let end_time = new Date('2000-01-01 ' + end).getTime();
      while (start_time <= end_time) {
        // i++;
        let h = new Date(start_time * 1).getHours();
        let m = new Date(start_time * 1).getMinutes();
        if (h < 10) {
          h = '0' + h;
        }
        if (m < 10) {
          m = '0' + m;
        }
        let hm = h + ':' + m;
        let obj = {};
        if (hm == data[i].hm) {
          obj = {
            all_on_hand: data[i].all_on_hand,
            in_player: data[i].in_player,
            on_hand: data[i].on_hand,
            out_player: data[i].out_player,

            all_on_child: data[i].all_on_child,
            in_child: data[i].in_child,
            on_child: data[i].on_child,
            out_child: data[i].out_child
          };
          i = i == data.length - 1 ? i : i + 1;
        } else {
          obj = {
            all_on_hand: i == 0 ? 0 : data[i - 1].all_on_hand,
            in_player: 0,
            on_hand: 0,
            out_player: 0,

            all_on_child: i == 0 ? 0 : data[i - 1].all_on_child,
            in_child: 0,
            on_child: 0,
            out_child: 0
          };
        }
        obj.hm = hm;
        obj.date = data[i].date ? data[i].date : this.formInline.start_time;
        obj.time = obj.date + ' ' + hm;
        complementData.push(obj);
        start_time += 1000 * 60 * 30;
      }
      return complementData;
    }
  }
};
</script>

<style scoped lang="scss">
div.customContainer {
  overflow-y: auto;
}
.contrast {
  margin-bottom: 20px;
  text-align: right;
  position: relative;
  .check_dialog {
    width: 320px;
    top: 40px;
    right: 0;
    z-index: 100;
  }
}
</style>